#!/bin/bash

# 设置错误时退出
set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查命令是否存在
check_command() {
    if ! command -v $1 &> /dev/null; then
        print_error "$1 命令未找到，请先安装"
        exit 1
    fi
}

# 检查必要的命令
print_info "检查必要的命令..."
check_command "docker"
check_command "git"

# 配置变量
REGISTRY="crpi-8vadjonh2nyqyvih.cn-shanghai.personal.cr.aliyuncs.com"

# 获取当前git仓库名称
print_info "获取当前git仓库信息..."
if [ -d ".git" ]; then
    # 获取远程仓库URL
    REMOTE_URL=$(git config --get remote.origin.url)
    if [ -z "$REMOTE_URL" ]; then
        print_error "无法获取git远程仓库URL"
        exit 1
    fi
    
    # 从URL中提取仓库名称
    if [[ $REMOTE_URL == *"github.com"* ]]; then
        # GitHub格式: https://github.com/owner/repo.git 或 git@github.com:owner/repo.git
        REPO_NAME=$(basename -s .git "$REMOTE_URL")
    elif [[ $REMOTE_URL == *"gitlab"* ]]; then
        # GitLab格式
        REPO_NAME=$(basename -s .git "$REMOTE_URL")
    else
        # 其他格式，尝试提取
        REPO_NAME=$(basename -s .git "$REMOTE_URL")
    fi
    
    # 获取组织/用户名（假设格式为 owner/repo）
    if [[ $REMOTE_URL == *"/"* ]]; then
        OWNER=$(echo "$REMOTE_URL" | sed -E 's/.*[:\/]([^\/]+\/[^\/]+)\.git.*/\1/' | cut -d'/' -f1)
        REPOSITORY="${OWNER}/${REPO_NAME}"
    else
        # 如果无法解析，使用默认格式
        REPOSITORY="cityark/${REPO_NAME}"
    fi
    
    print_success "检测到仓库: ${REPOSITORY}"
else
    print_error "当前目录不是git仓库"
    exit 1
fi

IMAGE_NAME="${REGISTRY}/${REPOSITORY}"

# 步骤1: 构建Docker镜像
print_info "步骤1: 构建Docker镜像..."
if [ -f "Dockerfile" ]; then
    docker build --platform linux/amd64 -t ${IMAGE_NAME}:latest .
    print_success "Docker镜像构建完成"
else
    print_error "Dockerfile 不存在"
    exit 1
fi

# 步骤2: 获取当前git commit的id（8位）
print_info "步骤2: 获取当前git commit ID..."
COMMIT_ID=$(git rev-parse --short=8 HEAD)
if [ -z "$COMMIT_ID" ]; then
    print_error "无法获取git commit ID"
    exit 1
fi
print_success "获取到commit ID: ${COMMIT_ID}"

# 步骤3: 登录到阿里云容器镜像服务
print_info "步骤3: 登录到阿里云容器镜像服务..."
print_warning "请确保您已经配置了阿里云容器镜像服务的访问凭证"
docker login --username=cityark@cityark -p cityark123 ${REGISTRY}
print_success "登录成功"

# 步骤4: 使用commit id来tag docker镜像
print_info "步骤4: 使用commit ID标记Docker镜像..."
docker tag ${IMAGE_NAME}:latest ${IMAGE_NAME}:${COMMIT_ID}
print_success "镜像标记完成: ${IMAGE_NAME}:${COMMIT_ID}"

# 步骤5: 推送镜像到阿里云容器镜像服务
print_info "步骤5: 推送镜像到阿里云容器镜像服务..."

# 推送latest标签
print_info "推送latest标签..."
docker push ${IMAGE_NAME}:latest

# 推送commit ID标签
print_info "推送commit ID标签..."
docker push ${IMAGE_NAME}:${COMMIT_ID}

print_success "镜像推送完成！"
print_info "镜像地址:"
echo "  Latest: ${IMAGE_NAME}:latest"
echo "  Commit: ${IMAGE_NAME}:${COMMIT_ID}"

print_success "所有步骤完成！" 